//
//  QDLifeTableHeaderView.m
//  QDMetroClient
//
//  Created by YueWen on 2019/2/18.
//  Copyright © 2019 YueWen. All rights reserved.
//

#import "QDLifeTableHeaderView.h"
#import "QDCarouselItem.h"
#import "QDItemButtonCollectionViewCell.h"
#import "RITLCollectionViewPageFlowLayout.h"
#import "QDMetroClient-Swift.h"

/// 轮播的高度
CGFloat QDLifeCycleHeight(void) {
    
    //轮播
    CGFloat scale = 140.0 / 335;
    CGFloat itemWidth = UIScreen.mainScreen.ritl_width - 20 - 20;
    return (NSInteger)ceil(itemWidth * scale) + 16;
}


/// 子模块的高度
CGFloat QDLifeItemsHeight(void) {
    return 85;
}


/// 广告的高度
CGFloat QDAdItemsHeight(void){

    CGFloat scale = 60.0 / 335;
    CGFloat itemWidth = UIScreen.mainScreen.ritl_width - 20 - 20;
    return (NSInteger)ceil(itemWidth * scale) + 11;
}


/// header的高度
CGFloat QDLifeTableHeaderViewHeight(BOOL hasCycle,BOOL hasItems, BOOL hasAd) {
    
    CGFloat height = 0.0;
    
    height += (hasCycle ? QDLifeCycleHeight() : 0.0);
    height += (hasItems ? QDLifeItemsHeight() : 0.0);
    height += (hasAd ? QDAdItemsHeight() : 0.0);
    
    return  height + 9;
}




@interface QDLifeTableHeaderView()<RITLSDCycleScrollViewDataSource,SDCycleScrollViewDelegate>

/// 布局对象
@property (nonatomic, strong) RITLCollectionViewPageFlowLayout *flowLayout;
/// 广告布局对象
@property (nonatomic, strong) RITLCollectionViewPageFlowLayout *adFlowLayout;

/// 顶部的轮播数据源
@property (nonatomic, copy, nullable)NSArray <QDCarouselItem *> *carouses;
/// 顶部的item
@property (nonatomic, copy, nullable)NSArray <QDCarouselItem *> *items;
/// 顶部的广告
@property (nonatomic, copy, nullable)NSArray <QDCarouselItem *> *ads;
/// 遮罩视图
@property (nonatomic, strong) UIImageView * shadowImageView;

@end

@implementation QDLifeTableHeaderView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self buildView];
    }
    return self;
}


- (void)buildView {
    
    self.cycleView.autoScroll = false;
    self.cycleView.pageEnable = false;
    [self addSubview:self.cycleView];
    [self makeCycleViewConstraints:self.cycleView];
    
    self.itemsView.autoScroll = false;
    self.itemsView.infiniteLoop = false;
    [self addSubview:self.itemsView];
    
    self.shadowImageView = UIImageView.new;
    self.shadowImageView.image = @"nav_shadow_bottom".ritl_image;
    [self addSubview:self.shadowImageView];
    
    self.adsView.autoScroll = false;
    self.adsView.infiniteLoop = false;
    [self addSubview:self.adsView];
    
    
    [self.itemsView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.height.mas_equalTo(85);
        make.top.offset(QDLifeCycleHeight());
    }];
    
    
    [self.shadowImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.offset(0);
        make.height.mas_equalTo(9);
    }];
    
    
    [self.adsView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.height.mas_equalTo(QDAdItemsHeight());
    }];
}



- (void)makeCycleViewConstraints:(RITLSDCycleScrollView *)view {
    
    if (!view.superview) { return; }
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.top.offset(16);
        make.height.mas_equalTo(QDLifeCycleHeight() - 16);
    }];
}

#pragma mark - <RITLSDCycleScrollViewDataSource>

//- (Class)cycleViewCustomCollectionViewCellClass:(RITLSDCycleScrollView *)cycleView {
//
//    // 如果是轮播图返回SDCollectionViewCell;如果是子模块，返回QDItemButtonCollectionViewCell
//    return ![cycleView isEqual:self.itemsView] ? SDCollectionViewCell.class : QDItemButtonCollectionViewCell.class;
//}

//TODO: 分类方法待重构
//TODO: 分类方法待重构
//TODO: 分类方法待重构


- (NSDictionary<NSString *,Class> *)cycleViewAllRegisterCellClasses:(RITLSDCycleScrollView *)cycleView {
    
    return @{@"sdCell": SDCollectionViewCell.class, //普通的图片样式
             @"itemCell": QDItemButtonCollectionViewCell.class, //子模块样式
             @"hezi": QDHDHZCycleCollectionViewCell.class // 活动盒子的样式
             };
}



- (NSString *)cycleViewIdentifer:(RITLSDCycleScrollView *)cycleView atIndexPath:(NSIndexPath *)indexPath {
    
    //如果是子模块
    if ([cycleView isEqual:self.itemsView]) {
        return @"itemCell";
    }
    
    //如果顶部轮播
    if ([cycleView isEqual:self.cycleView]){
        return self.carouses[indexPath.item].isBox ? @"hezi" : @"sdCell";
    }
    
    //广告
    return self.ads[indexPath.item].isBox ? @"hezi" : @"sdCell";
}



- (void)cycleView:(RITLSDCycleScrollView *)cycleView setupCustomCell:(UICollectionViewCell<RITLSDCycleScrollViewCell> *)cell forIndex:(NSIndexPath *)indexPath {
    
    // 轮播模块
    if ([cycleView isEqual:self.cycleView]) {
        
        if ([cell isKindOfClass:SDCollectionViewCell.class]){//如果是图片
            
            SDCollectionViewCell *sdImageCell = (SDCollectionViewCell *)cell;
            sdImageCell.imageView.layer.cornerRadius = 8;
            sdImageCell.imageView.clipsToBounds = true;
            return;
        }
        
        QDHDHZCycleCollectionViewCell *heziCell = (QDHDHZCycleCollectionViewCell *)cell;
        
        //设置代理
        heziCell.bannerView.delegate = self.heziDelegate;
        [heziCell.bannerView setPositionKey:self.carouses[indexPath.item].boxKey properties:self.hzProperties];
        
        return;
    }
    
    /// 广告模块
    if ([cycleView isEqual:self.adsView]){
        
        if ([cell isKindOfClass:SDCollectionViewCell.class]){//如果是图片
            
            SDCollectionViewCell *sdImageCell = (SDCollectionViewCell *)cell;
            sdImageCell.imageView.contentMode = UIViewContentModeScaleAspectFill;
            sdImageCell.imageView.clipsToBounds = true;
            return;
        }
        
        QDHDHZCycleCollectionViewCell *heziCell = (QDHDHZCycleCollectionViewCell *)cell;
        
        //设置代理
        heziCell.bannerView.delegate = self.heziDelegate;
        [heziCell.bannerView setPositionKey:self.ads[indexPath.item].boxKey properties:self.hzProperties];
        
        return;
    }
    
    // 子模块
    ((QDItemButtonCollectionViewCell *)cell).itemButton.titleLabel.text = self.items[indexPath.item].function;
}


- (UICollectionViewLayout *)cycleScollViewcustomCollectionViewLayout:(RITLSDCycleScrollView *)cycleView {
    
    //轮播样式
    if ([self.cycleView isEqual:cycleView]) {

        RITLCollectionViewPageFlowLayout *flowLayout = RITLCollectionViewPageFlowLayout.new;
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        flowLayout.sectionInset = UIEdgeInsetsMake(0, 20, 0, 20);
        flowLayout.minimumLineSpacing = 10;
        flowLayout.minimumInteritemSpacing = CGFLOAT_MIN;
        
        // 计算item的Size
        CGFloat scale = 140.0 / 335;
        CGFloat itemWidth = UIScreen.mainScreen.ritl_width - 20 - 20;
        flowLayout.itemSize = CGSizeMake(itemWidth, itemWidth * scale);
        
        self.flowLayout = flowLayout;
        
        return flowLayout;
    }
    
    //广告样式
    if ([self.adsView isEqual:cycleView]){
        
        RITLCollectionViewPageFlowLayout *flowLayout = RITLCollectionViewPageFlowLayout.new;
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        flowLayout.sectionInset = UIEdgeInsetsMake(0, 20, 0, 20);
        flowLayout.minimumLineSpacing = 10;
        flowLayout.minimumInteritemSpacing = CGFLOAT_MIN;
        
        CGFloat scale = 60.0 / 335;
        CGFloat itemWidth = UIScreen.mainScreen.ritl_width - 20 - 20;
        flowLayout.itemSize = CGSizeMake(itemWidth, itemWidth * scale);
        

        self.adFlowLayout = flowLayout;
        return flowLayout;
    }
    
    
    //子模块样式
    return ({
        

        UICollectionViewFlowLayout *flowLayout = [UICollectionViewFlowLayout new];
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        flowLayout.itemSize = @[@45,@64].ritl_size;
//            flowLayout.sectionInset = UIEdgeInsetsMake(12, 0, 0, 0);
        
        CGFloat minimumLineSpacing = (UIScreen.mainScreen.ritl_width - flowLayout.itemSize.width * 4) / (4 + 1);
        
        flowLayout.minimumLineSpacing = minimumLineSpacing;
        flowLayout.sectionInset = UIEdgeInsetsMake(12, minimumLineSpacing, 0, minimumLineSpacing);
        
        flowLayout;
    });
}


- (BOOL)cycleViewShouldResetCollectionWithCustomScrollPosition:(RITLSDCycleScrollView *)cycleView {
    return ![cycleView isEqual:self.itemsView];//如果不是子模块，就是用自定义的scroll position
}


- (UICollectionViewScrollPosition)cycleViewCustomCollectionViewScrollPosition:(RITLSDCycleScrollView *)cycleView {
    return UICollectionViewScrollPositionCenteredHorizontally;
}


- (NSInteger)cycleView:(RITLSDCycleScrollView *)cycleView currentIndexWithContentOffset:(CGPoint)contentOffset {
    
    if ([cycleView isEqual:self.itemsView]) { return -1; }
    if ([cycleView isEqual:self.adsView]){
        return [self.adFlowLayout itemAtIndexPathForCollectionWithContentOffsetX:contentOffset.x];
    }
    
    return [self.flowLayout itemAtIndexPathForCollectionWithContentOffsetX:contentOffset.x];
}


- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index {
 
    //轮播
    if ([cycleScrollView isEqual:self.cycleView]) {
        [self.actor qdLifeTableHeaderView:self bannerIndex:index]; return;
    }
    
    //子模块
    if ([cycleScrollView isEqual:self.itemsView]) {
        [self.actor qdLifeTableHeaderView:self itemIndex:index]; return;
    }
    
    //广告
    [self.actor qdLifeTableHeaderView:self adIndex:index];
}

#pragma mark - Lazy

- (RITLSDCycleScrollView *)cycleView {
    
    if (!_cycleView) {
        
        _cycleView = [RITLSDCycleScrollView new];
        
        RITLSDCycleScrollView *view = _cycleView;
        view.dataSource = self;
        view.delegate = self;
        view.pageEnable = false;
        view.backgroundColor = UIColor.whiteColor;
    }
    
    return _cycleView;
}


- (RITLSDCycleScrollView *)itemsView {

    if (!_itemsView) {

        _itemsView = [RITLSDCycleScrollView new];
        _itemsView.dataSource = self;
        _itemsView.delegate = self;
        _itemsView.backgroundColor = UIColor.whiteColor;
    }

    return _itemsView;
}


- (RITLSDCycleScrollView *)adsView {
    
    if (!_adsView) {
        
        _adsView = [RITLSDCycleScrollView new];
        _adsView.dataSource = self;
        _adsView.delegate = self;
        _adsView.autoScroll = false;
        _adsView.pageEnable = false;
        _adsView.backgroundColor = UIColor.whiteColor;
    }
    
    return _adsView;
}


#pragma mark - Update

- (void)updateWithItems:(__kindof NSArray<QDCarouselItem *> *)carouses
                  items:(__kindof NSArray<QDCarouselItem *> *)items
               complete:(void (^)(QDLifeTableHeaderView * _Nonnull))complete
{
    [self updateWithItems:carouses items:items ads:@[] complete:complete];
}


- (void)updateWithItems:(__kindof NSArray<QDCarouselItem *> *)carouses
                  items:(__kindof NSArray<QDCarouselItem *> *)items
                    ads:(__kindof NSArray<QDCarouselItem *> *)ads
               complete:(void (^)(QDLifeTableHeaderView * _Nonnull))complete {
    
    
    //计算自己的高度
    self.ritl_height = QDLifeTableHeaderViewHeight(carouses.count >= 1,true,ads.count > 0);
    
    //进行赋值
    self.carouses = carouses;
    self.items = items;
    self.ads = ads;
    
    //进行UI设置
    self.cycleView.autoScroll = carouses.count > 1;
    self.cycleView.infiniteLoop = carouses.count > 1;
    self.cycleView.imageURLStringsGroup = [carouses ritl_map:^id _Nonnull(QDCarouselItem * _Nonnull obj) {
        return obj.imgUrl;
    }];
    
    //子模块
    self.itemsView.imageURLStringsGroup = [items ritl_map:^id _Nonnull(QDCarouselItem * _Nonnull obj) {
        return obj.imgUrl;
    }];
    
    //广告
    if (ads.count > 0){
        self.adsView.imageURLStringsGroup = [ads ritl_map:^id _Nonnull(QDCarouselItem * _Nonnull obj) {
            return obj.imgUrl;
        }];
    }
    
    self.adsView.hidden = (ads.count == 0);
    self.shadowImageView.hidden = !self.adsView.hidden;
    
    complete(self);
    
}

@end
